// 作用域：全局作用域，词法作用域，动态作用域，函数作用域

// 全局作用域声明变量
aVariable = "Outer";

function aFun() {
    var aVariable = "Middle";

    return _.map([1, 2, 3], function(e) {
        var aVariable = "In";
        return [aVariable, e].join(" ");
    });
}

console.log(aFun()); // ["In 1", "In 2", "In 3"]

// 模拟动态作用域

// 定义全局作用域表
var globals = {};

function makeBindFun(resolver) {
    return function(k, v) {
        var stack = globals[k] || [];
        globals[k] = resolver(stack, v);
        return globals;
    }
}

// 绑定变量到全局作用域
var stackBinder = makeBindFun(function(stack, v) {
    stack.push(v);
    return stack;
});

// 从全局作用域表中释放变量
var stackUnbinder = makeBindFun(function(stack, v) {
    stack.pop();
    return stack;
});

// 查询全局作用域绑定的值
var dynamicLookup = function(k) {
    var solt = globals[k] || [];
    return _.last(solt);
}